# -*- coding: utf-8 -*-
# @Time    : 2020/7/16 14:43
# @Author  : ZhaoHexin
# @File    : CreateSso.py
# @Description  : 单条创建sso

import os
from CreateSsoFile.BasicMethod import BasicMethod


class CreateSso:
    def __init__(self, usernames, passwords, majorcodes, majornames, regioncodes, path):
        self.user_names = usernames
        self.passwords = passwords
        self.majorcodes = majorcodes
        self.majornames = majornames
        self.regioncodes = regioncodes
        self.path = path

    def create(self):
        """
        创建sso文件
        :return:
        """
        # 组装sso文件内容
        sso = self.assemble()
        # 对组装内容进行加密
        encrypt = BasicMethod().des_encrypt(sso.get("text").encode("utf-8"))
        # 生成sso文件
        with open(os.path.join(self.path, "mdm_auto_account.xml"), "w", encoding="UTF-8") as f:
            f.write(encrypt)
        return sso.get("create_info")

    def assemble(self):
        texts = ""
        create_info = []
        text_title = """<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>\n<Accounts>\n"""
        text_ending = "</Accounts>"
        for i in range(len(self.majorcodes)):
            try:
                majorname = self.majornames[i]
            except:
                try:
                    majorname = self.majornames[0]
                except:
                    majorname = "没有输入专业标识名称哦！"
            try:
                password = self.passwords[i]
            except:
                password = self.passwords[0]
            try:
                user_name = self.user_names[i]
            except:
                user_name = self.user_names[0]
            try:
                regioncode = self.regioncodes[i]
            except:
                regioncode = self.regioncodes[0]
            # 以专业代码为基准，获取所有对应信息，若获取不到，则用第一个
            text = f"""	<AccountInfo>
            <Major code="{self.majorcodes[i]}" name="{majorname}" />
            <Version code="0" version="" />
            <AccountId id="1000514" />
            <AccountPwd pwd="{password}" />
            <AccountDisplayName name="{user_name}" />
            <PhoneNumber phonenum="13800138000" />
            <RegionCode value="{regioncode}01" />\n	</AccountInfo>\n"""
            texts += text
            create_info.append({"username": user_name, "password": password, "majorcode": self.majorcodes[i],
                                "majorname": majorname, "regioncode": regioncode, "path": self.path})
        return {"text": text_title + texts + text_ending, "create_info": create_info}


if __name__ == '__main__':
    user_name = ["user"]
    password = ["1"]
    majorcode = ["2019ydldldc_00GJ", "rkbd2019_00GJ"]
    majorname = []
    regioncode = ["660807511515000"]
    path = os.path.abspath(".")
    Create = CreateSso(user_name, password, majorcode, majorname, regioncode, path)
    print(Create.create())
